//
//  IMConversationListViewController.m
//  MLIM
//
//  Created by molon on 15/6/24.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "IMConversationListViewController.h"
#import "IMConversationTableViewCell.h"
#import "IMCommon.h"
#import "IMConversationViewController.h"
#import "IMManager.h"
#import <AFNetworkReachabilityManager.h>
#import <EmptyTipsView.h>

@interface IMConversationListViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *sortedIMVersations;

@property (nonatomic, strong) UIView *notReachabilityTipView;

@property (nonatomic, strong) EmptyTipsView *emptyTipsView;

@end

@implementation IMConversationListViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        NSAssert(![[IMManager manager] isMemberOfClass:[IMManager class]], @"必须先在appLauched头部执行任何自定义的IMManager方法，以便于此单例被自定义的IMManager初始化。例如[[LeanIMManager manager]appLauchedXXXXX]");
        [[AFNetworkReachabilityManager sharedManager]startMonitoring];
        
        self.indicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refresh) name:MLIM_IMConversation_UpdateDetail_Notification object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateTitle:) name:MLIM_IMManagerStatus_Updated_Notification object:nil];
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reachabilityDidChange:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MLIM_IMManagerStatus_Updated_Notification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MLIM_IMConversation_UpdateDetail_Notification object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = self.tableView.backgroundColor = IMCONFIGM.backgroundColorForIMConversationListViewController;
    
    self.title = [self defaultTitle];
    
    [self.view addSubview:self.tableView];
    
    [self updateTitle:nil];
    
    [self refresh];
    
    //第一次也检测下网络，因为可能之前的网络状态更改通知并没有捕获到
    [self reachabilityDidChange:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

#pragma mark - getter
- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc]init];
        tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        tableView.delegate = self;
        tableView.dataSource = self;
        [tableView registerClass:[IMConversationTableViewCell class] forCellReuseIdentifier:[IMConversationTableViewCell cellReuseIdentifier]];
        
        _tableView = tableView;
    }
    return _tableView;
}

- (UIView *)notReachabilityTipView
{
    if (!_notReachabilityTipView) {
        _notReachabilityTipView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frameWidth, 44.0f)];
        _notReachabilityTipView.backgroundColor = [UIColor colorWithRed:0.988 green:0.847 blue:0.851 alpha:1.000];
        //subview
        UIImageView *warningImageView = [[UIImageView alloc]initWithImage:IMIMG(@"感叹号")];
        warningImageView.contentMode = UIViewContentModeScaleAspectFit;
        warningImageView.frame = CGRectMake(10, 0, 40.0f, _notReachabilityTipView.frameHeight);
        [_notReachabilityTipView addSubview:warningImageView];
        
        UILabel *tipLabel = [[UILabel alloc]initWithFrame:CGRectMake(warningImageView.frameRight+10.0f, 0, _notReachabilityTipView.frameWidth-warningImageView.frameRight-10.0f*2, _notReachabilityTipView.frameHeight)];
        tipLabel.text = @"当前网络不可用，请检查你的网络设置";
        tipLabel.font = [UIFont systemFontOfSize:14.5f];
        [_notReachabilityTipView addSubview:tipLabel];
    }
    return _notReachabilityTipView;
}

- (EmptyTipsView *)emptyTipsView
{
    if (!_emptyTipsView) {
        EmptyTipsView* emptyTipsView = [EmptyTipsView new];
        emptyTipsView.label.text = @"当前没有会话";
        emptyTipsView.imageView.image = IMCONFIGM.tipsImageWhenNoConversation;
        _emptyTipsView = emptyTipsView;
    }
    return _emptyTipsView;
}

#pragma mark - layout
- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    self.tableView.frame = self.view.bounds;
}

#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sortedIMVersations.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMConversationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[IMConversationTableViewCell cellReuseIdentifier] forIndexPath:indexPath];
    
    IMConversation *imConv = self.sortedIMVersations[indexPath.row];
    cell.imConv = imConv;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMConversation *imConv = self.sortedIMVersations[indexPath.row];
    return [IMConversationTableViewCell heightForObject:imConv maxWidth:self.view.frameWidth];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    IMConversationViewController *vc = nil;
    if (self.customIMConversationViewControllerBlock) {
        vc = self.customIMConversationViewControllerBlock();
    }else{
        vc = [IMConversationViewController new];
    }
    if (!vc) {
        return;
    }
    vc.imConv = self.sortedIMVersations[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - refresh
- (void)refresh
{
    self.sortedIMVersations = [IMCM sortedValidIMConversations];
    [self.tableView reloadData];
    if (self.sortedIMVersations.count>0) {
        self.tableView.backgroundView = nil;
    }else{
        self.tableView.backgroundView = self.emptyTipsView;
    }
    
    NSInteger unreadCountSum = [[self.sortedIMVersations valueForKeyPath:@"@sum.unreadCount"]integerValue];
    UITabBarItem *tabBarItem = self.navigationController?self.navigationController.tabBarItem:self.tabBarItem;
    
    if (self.navigationController&&![[self.navigationController.viewControllers firstObject]isEqual:self]) {
        //如果不是第一个，也算了
        tabBarItem = nil;
    }
    
    NSString *title = [self defaultTitle];
    if (unreadCountSum==0) {
        tabBarItem.badgeValue = nil;
        self.title = title;
    }else{
        tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",unreadCountSum];
        self.title = [NSString stringWithFormat:@"%@(%ld)",title,unreadCountSum];
    }
    
    if ([IMManager manager].status==IMManagerStatusConnected) {
        [self displayTitleViewWithTitle:self.title showIndicator:NO];
    }
    
    tabBarItem.title = title;
    
    if (self.needUpdateApplicationBadgeNumberBlock) {
        self.needUpdateApplicationBadgeNumberBlock(unreadCountSum);
    }
}

- (void)updateTitle:(NSNotification*)notification
{
    IMManagerStatus status = IMManagerStatusNone;
    if (!notification) {
        status = [IMManager manager].status;
    }else{
        status = [notification.userInfo[@"status"] integerValue];
    }
    
    NSString *title = nil;
    
    if (status==IMManagerStatusConnected) {
        title = self.title;
    }else{
        if (self.titleForIMManagerStatusBlock) {
            title = self.titleForIMManagerStatusBlock(status);
        }
        if (!title) {
            title = @"";
            switch (status) {
                case IMManagerStatusNone:
                    title = @"未登录";
                    break;
                case IMManagerStatusPaused:
                    title = @"未连接";
                    break;
                case IMManagerStatusConnecting:
                    title = @"连接中";
                    break;
                default:
                    break;
            }
        }
    }
    BOOL showIndicator = status==IMManagerStatusConnecting;
    [self displayTitleViewWithTitle:title showIndicator:showIndicator];
}

- (void)displayTitleViewWithTitle:(NSString*)title showIndicator:(BOOL)showIndicator
{
    title = title?:@"";
    //头部view
    UILabel *label = [UILabel new];
    NSMutableAttributedString *attributedTilte = [[NSMutableAttributedString alloc]initWithString:title];
    if ([UINavigationBar appearance].titleTextAttributes) {
        [attributedTilte addAttributes:[UINavigationBar appearance].titleTextAttributes range:NSMakeRange(0, attributedTilte.length)];
    }else{
        label.font = [UIFont boldSystemFontOfSize:18.0f];
    }
    
    if ([UINavigationBar appearance].tintColor) {
        label.textColor = [UINavigationBar appearance].tintColor;
    }
    
    label.attributedText = attributedTilte;
    [label sizeToFit];
    
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, label.frameWidth, self.navigationController.navigationBar.intrinsicContentSize.height)];
    label.frame = CGRectMake(0, 0.0f, label.frameWidth, titleView.frameHeight);
    [titleView addSubview:label];
    
    if (showIndicator) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:self.indicatorViewStyle];
        indicator.frameOrigin = CGPointMake(-indicator.frameWidth-3.0f, (titleView.frameHeight-indicator.frameHeight)/2);
        [titleView addSubview:indicator];
        [indicator startAnimating];
    }
    
    self.navigationItem.titleView = titleView;
}

- (void)reachabilityDidChange:(NSNotification*)notification
{
    self.tableView.tableHeaderView = [[AFNetworkReachabilityManager sharedManager]isReachable]?nil:self.notReachabilityTipView;
}

#pragma mark - other
- (NSString*)defaultTitle
{
    NSString *title = nil;
    if (self.titleForIMManagerStatusBlock) {
        title = self.titleForIMManagerStatusBlock(IMManagerStatusConnected);
    }
    if (!title) {
        title = @"聊天";
    }
    return title;
}


@end
